package com.recipedb.recipedb.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.*;
import java.util.Map;

@RestController
@RequestMapping("/api/upload")
public class UploadController {

    // 建议在 application.yml 中设置绝对路径
    @Value("${upload.base-path:/var/www/recipe-app/uploads}")
    private String basePath;

    @PostMapping
    public ResponseEntity<?> uploadFile(@RequestParam("file") MultipartFile file,
                                        @RequestParam("path") String path) {
        try {
            // 基础安全检查，防止路径穿越
            if (path.contains("..")) {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                        .body("非法路径");
            }

            Path savePath = Paths.get(basePath).resolve(path).normalize();
            Files.createDirectories(savePath.getParent());

            // 直接覆盖已有文件
            file.transferTo(savePath.toFile());

            return ResponseEntity.ok(Map.of(
                    "message", "上传成功（文件已覆盖同名文件）",
                    "path", "/uploads/" + path
            ));
        } catch (IOException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("文件保存失败：" + e.getMessage());
        }
    }
}
